<template>
	<div class="main">
		<div style="font-size: 16px; color: #333; margin-bottom: 12px">
			投保手机号验证
		</div>
		<el-form :model="formData" :rules="rules" label-width="64px" ref="form">
			<el-form-item label="手机号" prop="phone">
				<el-input readonly v-model="phone" size="mini"></el-input>
			</el-form-item>
			<el-form-item label="验证码" prop="verify">
				<el-input
					ref="verify-input"
					v-model="formData.verify"
					size="mini"
					placeholder="请输入验证码"
				></el-input>
			</el-form-item>

			<div style="text-align: center; margin-top: 20px">
				<el-button type="primary" @click="verifyCode" style="width: 100px"
					>确认</el-button
				>
			</div>
		</el-form>
	</div>
</template>

<script>
import { getVerify, verifyCode, getBusinessById } from '@/api'
export default {
	data() {
		return {
			rules: {
				verify: [
					{
						message: '请输入验证码',
						validator: (rule, value, callback) =>
							value.length > 0 ? callback() : callback(new Error(rule.message))
					}
				]
			},
			formData: {
				verify: ''
			},
			phone: ''
		}
	},
	computed: {
		businessId() {
			return this.$route.query.businessId || ''
		}
	},
	mounted() {
		if (this.businessId) {
			getVerify(this.businessId)
				.then((res) => {
					this.phone = res.data
					this.$message.success({
						message: '验证码已发送至您的手机',
						duration: 10000,
						showClose: true
					})
					this.$refs['verify-input'].focus()
				})
				.catch(() => {
					this.$message.error({
						message: '自动发送验证码失败，请刷新重试',
						duration: 0,
						showClose: true
					})
				})
		}
	},
	methods: {
		verifyCode() {
			this.$refs.form.validate((valid) => {
				if (valid) {
					verifyCode({
						businessId: this.businessId,
						code: this.formData.verify
					}).then(() => {
						getBusinessById(this.businessId).then((res) => {
							const { insuranceFileUrl, productId } = res.data
							sessionStorage.setItem('isVerifyBusiness', this.businessId)
							this.$router.push({
								name: 'Stamp',
								query: {
									docUrl: insuranceFileUrl,
									businessId: this.businessId,
									productId: productId
								}
							})
						})
					})
				}
			})
		}
	},
	components: {}
}
</script>

<style lang="scss" scoped="scoped">
.main {
	width: 330px;
	border: 1px solid #e6e6e6;
	border-radius: 12px;
	padding: 25px;
	position: fixed;
	left: 50%;
	top: 30%;
	transform: translate(-50%);
}

::v-deep {
	.el-form-item:not(.is-error) {
		margin-bottom: 0;
	}
}
</style>
